﻿using FastEndpoints.Security;
using vite_core.Common;
using vite_net.Common;
using vite_services;

namespace vite_net.Controllers.User.Login
{
    public class LoginEndpoint : ViteNetEndpoint<Request_Login, Result<Response_Login>, LoginMapper>
    {
        private readonly IConfiguration _configuration;
        private readonly UserServices _userServices;
        public LoginEndpoint(IConfiguration configuration, UserServices userServices)
        {
            _configuration = configuration;
            _userServices = userServices;
        }

        public override void Configure()
        {
            Post("/auth/login");
            AllowAnonymous();
        }

        public override async Task HandleAsync(Request_Login req, CancellationToken ct)
        {
            var userId = GetCurrentUserId();
            var user = await _userServices.GetUserByUserNameAsync(req.username.Trim());
            if (user is null)
                AddError(r => r.username, "用户名不存在!");
            ThrowIfAnyErrors(); // If there are errors, execution shouldn't go beyond this point  ThrowError("The supplied credentials are invalid!"); 报错提示

            // 校验密码
            if (user != null && user.Password == req.password.ToMD5())
            {
                // 获取roles
                var roles_Code_Id = await _userServices.GetUserRolesByUserId(user.Id);

                var jwtToken = JwtHelpler.CreateToken(_configuration.GetSection("JWT:SigningKey").Value ?? string.Empty,
                    roles_Code_Id.Item1, user.Username ?? string.Empty, user.Id.ToString());

                var responseData = new Response_Login()
                {
                    AccessToken = jwtToken,
                    TokenType = "JWT",
                    RefreshToken = "",
                    Expires = "",
                };


                await SendAsync(Result<Response_Login>.Ok(responseData));
            }
            else
            {
                await SendAsync(Result<Response_Login>.Fail("密码不正确！"));
            }
        }


    }


}
